<?php
namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\User;
use Illuminate\Http\Request;
use App\News;
use App\Friendship;
use DB;

class FriendsController extends Controller
{
	private function getCurrentUser(){
		$uc = new UserController();
		return $uc->getCurrentUser();
	}
	
	public function homepage(){
		return view('friends.friends',['name'=>$this->getCurrentUser()->name,'myId'=>$this->getCurrentUser()->id,'requests'=>$this->friendshipRequestList(),'friends'=>$this->getFriendList(),'news'=>$this->getNews()]);
	}
	
	public function addFriend(Request $r){
		$user=$this->getCurrentUser()->id;
		$targetName=$r->get('addFriendName');
		$targetUser=User::where('name','=',$targetName)->first();
		if($targetUser==null){
			return $this->homepage();
		}
		$target=$targetUser->id;
		if($target==$user){
			return $this->homepage();
		}
		$exsit=Friendship::query()->where('me','=',$user)->where('friend','=',$target)->get()->count();
		if($exsit){
			return $this->homepage();
		}
		$fs=new Friendship();
		$fs->me=$user;
		$fs->friend=$target;
		$fs->agreed=false;
		$fs->save();
		return $this->homepage();
	}
	
	public function removeFriend(Request $r){
		$friendshipId=$r->get('friendshipId');
		$f1=Friendship::findOrNew($friendshipId);
		if($f1->friend==null){
			return $this->homepage();
		}
		DB::delete("delete from friendships where me=".$f1->friend." and friend=".$f1->me);
		Friendship::destroy($friendshipId);
		return $this->homepage();
	}
	
	public function getFriendList(){
				$friends=Friendship::query()->where('me','=',$this->getCurrentUser()->id)->where('agreed','=',true)->get();
		return $friends;
	}
	
	public function friendshipRequestList(){
		$requests=Friendship::query()->where('friend','=',$this->getCurrentUser()->id)->where('agreed','=',false)->get();
		return $requests;
	}
	
	public function acceptFriendshipReqest(Request $r){
		$friendshipId=$r->get('friendshipId');
		$friendship=Friendship::findOrNew($friendshipId);
		$friendship->agreed=true;
		$friendship->save();
		$friendship2=new Friendship();
		$friendship2->me=$friendship->friend;
		$friendship2->friend=$friendship->me;
		$friendship2->agreed=true;
		$friendship2->save();
		return $this->homepage();
	}
	
	public function refuseFriendshipRequest(Request $r){
		$friendshipId=$r->get('friendshipId');
		Friendship::destroy($friendshipId);
		return $this->homepage();
	}
	
	public function publishNews(Request $r){
		$userId=$this->getCurrentUser()->id;
		$news=new News();
		$news->publisher=$userId;
		$news->content=$r->get('content');
		$news->title=$r->get('title');
		$news->save();
		return $this->homepage();
	}

	public function getNews(){
		$userId=$this->getCurrentUser()->id;
		$news=DB::select("select * from news where news.publisher = ".$userId." or news.publisher in(select distinct friendships.friend from friendships where agreed=1 and friendships.me=".$userId.") order by updated_at desc");
		return $news;
	}
}